<template>
  <el-dialog
    :title="title"
    v-model="dialogVisible"
    width="400px"
    append-to-body
  >
    <el-form ref="formRef" :model="formData">
      <el-form-item label="继承年月" prop="inheritDate">
        <el-date-picker
          v-model="formData.inheritDate"
          type="month"
          value-format="YYYY-MM"
        />
      </el-form-item>
      <el-form-item label="目标年月" prop="targetDate">
        <el-date-picker
          v-model="formData.targetDate"
          type="month"
          value-format="YYYY-MM"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="text-center">
        <el-button type="primary" :loading="loading" @click="handleConfirm">
          确定
        </el-button>
        <el-button @click="handleCancel">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, computed } from 'vue'

const props = defineProps({
  modelValue: Boolean,         // 弹窗显隐
  title: {                     // 弹窗标题
    type: String,
    default: '继承设置'
  },
  loading: Boolean,            // 加载状态
  initialData: {               // 初始表单数据
    type: Object,
    default: () => ({
      inheritDate: '',
      targetDate: ''
    })
  }
})

const emit = defineEmits([
  'update:modelValue',
  'confirm',
  'cancel'
])

// 弹窗显示控制
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

// 表单实例
const formRef = ref(null)
// 表单数据
const formData = reactive({ ...props.initialData })

// 监听初始数据变化
watch(() => props.initialData, (newVal) => {
  Object.assign(formData, newVal)
}, { deep: true })

// 确认操作
const handleConfirm = async () => {
  try {
    await formRef.value.validate()
    emit('confirm', { ...formData })
  } catch (e) {
    console.log('表单验证失败', e)
  }
}

// 取消操作
const handleCancel = () => {
  emit('cancel')
  dialogVisible.value = false
}
</script>
